import { defineStore } from 'pinia'
import { ref } from 'vue'
import { userApi, type UserInfo, type LoginRequest } from '@/api/user'

export const useUserStore = defineStore('user', () => {
  const username = ref<string>('')
  const token = ref<string>('')
  const userId = ref<number | null>(null)
  const userInfo = ref<UserInfo | null>(null)
  const avatar = ref<string>('')

  const login = async (credentials: LoginRequest) => {
    try {
      const response = await userApi.login(credentials)
      
      // 检查响应格式并适配
      if (response && typeof response === 'object') {
        // 如果后端直接返回User对象
        if (response.id && response.username) {
          // 生成或获取token（这里假设后端应该返回token，如果没有则使用用户名作为临时token）
          const generatedToken = response.token || credentials.username
          
          token.value = generatedToken
          userId.value = response.id
          username.value = response.username
          
          // 保存到本地存储 - 添加null检查
          localStorage.setItem('token', generatedToken)
          localStorage.setItem('username', response.username)
          localStorage.setItem('userId', response.id?.toString() || '')
          
          return { success: true }
        }
        
        // 如果返回标准格式
        if (response.code === 1 && response.data) {
          token.value = response.data.token
          userId.value = response.data.id
          username.value = credentials.username
          
          // 保存到本地存储 - 添加null检查
          localStorage.setItem('token', response.data.token)
          localStorage.setItem('username', credentials.username)
          localStorage.setItem('userId', response.data.id?.toString() || '')
          
          return { success: true }
        }
        
        // 如果有错误信息
        if (response.msg) {
          throw new Error(response.msg)
        }
      }
      
      throw new Error('登录失败：响应格式不正确')
    } catch (error) {
      console.error('Login error:', error)
      throw error
    }
  }

  const fetchUserInfo = async () => {
    if (!token.value) {
      console.warn('No token found, cannot fetch user info')
      return null
    }
    
    try {
      const response = await userApi.getUserInfo()
      if (response.code === 1 && response.data) {
        userInfo.value = response.data
        // 同步头像到单独的状态 - 使用 avatarUrl 字段
        if (response.data.avatarUrl) {
          avatar.value = response.data.avatarUrl
        }
        return response.data
      }
      return null
    } catch (error) {
      console.error('Failed to fetch user info:', error)
      return null
    }
  }

  const uploadAvatar = async (file: File) => {
    try {
      const response = await userApi.uploadAvatar(file)
      if (response.code === 1 && response.data) {
        // 更新头像状态
        avatar.value = response.data
        // 如果userInfo存在，也更新其中的avatarUrl字段
        if (userInfo.value) {
          userInfo.value.avatarUrl = response.data
        }
        return response.data
      }
      throw new Error(response.msg || '上传失败')
    } catch (error) {
      console.error('Failed to upload avatar:', error)
      throw error
    }
  }

  const logout = () => {
    username.value = ''
    token.value = ''
    userId.value = null
    userInfo.value = null
    avatar.value = ''
    localStorage.removeItem('token')
    localStorage.removeItem('username')
    localStorage.removeItem('userId')
  }

  const initFromStorage = () => {
    const savedToken = localStorage.getItem('token')
    const savedUsername = localStorage.getItem('username')
    const savedUserId = localStorage.getItem('userId')
    
    if (savedToken && savedUsername) {
      token.value = savedToken
      username.value = savedUsername
      userId.value = savedUserId && savedUserId !== '' ? parseInt(savedUserId) : null
    }
  }

  return {
    username,
    token,
    userId,
    userInfo,
    avatar,
    login,
    logout,
    initFromStorage,
    fetchUserInfo,
    uploadAvatar
  }
})